package com.frxuexi.park2210.news

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.lib_base.entity.NewsBean
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.park2210.R
import com.frxuexi.park2210.adapter.NewsAdapter
import com.frxuexi.park2210.databinding.ActivityNewsBinding
import com.google.gson.Gson
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/app/NewsActivity")
@AndroidEntryPoint
class NewsActivity : BaseActivity<ActivityNewsBinding,NewsViewModel>() {
    val newsAdapter by lazy { NewsAdapter() }
    var page=0
    override fun initData() {
        vm.getNewsSuc.observe(this){
            val newsBean = Gson().fromJson(it, NewsBean::class.java)
            for (i in 0..newsBean.size-1){
                newsBean.get(i).type=i%2
            }
            newsAdapter.addData(newsBean)
            newsAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        binding.rvNews.apply {
            adapter=newsAdapter
            layoutManager=LinearLayoutManager(this@NewsActivity)
        }


        binding.smart.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page=0
                newsAdapter.data.clear()
                vm.getNews(mapOf("page" to page))
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                vm.getNews(mapOf("page" to page))
                binding.smart.finishLoadMore()
            }

        })

        binding.headerNews.apply {
            headerBack.setOnClickListener {
                finish()
            }
            headerTitle.setText("文化管理")
            headerAdd.visibility=View.VISIBLE
            headerAdd.setOnClickListener {
                ARouter.getInstance().build("/app/NewsAddActivity").navigation()
            }
        }


    }

    override fun onResume() {
        super.onResume()
        newsAdapter.data.clear()
        vm.getNews(mapOf("page" to page))
    }

}